﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace EasyChat.Client
{
    class Client
    {
        Socket socket;
        string Name;
        Thread SendThread;

        public Client()
        {
            Console.Title = "Easy Chat Client";

            Console.Write("IP: ");
            string IP = Console.ReadLine();

            Console.Write("Connecting to: " + IP + "...");
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(new IPEndPoint(Dns.GetHostEntry(IP).AddressList[0], 4567));
            }
            catch (Exception ex)
            { Console.WriteLine("\nError: " + ex.Message); Console.ReadKey(true); return; }
            Console.WriteLine("   Done!");

            Console.Write("Name: ");
            Name = Console.ReadLine();
            socket.Send(Encoding.ASCII.GetBytes(Name));

            SendThread = new Thread(SendMessages);
            SendThread.Start();

            while (true)
            {
                try
                {
                    byte[] message = new byte[4096 * 2];
                    socket.Receive(message);

                    for (int i = 0; i < Name.Length + 2; i++)
                        Console.Write("\b");

                    Console.WriteLine(Encoding.ASCII.GetString(RemoveNull(message)));

                    Console.Write(Name + ": ");
                }
                catch
                { Console.WriteLine("\nServer closed down!\nPress any key to exit but first enter!"); Console.ReadKey(true); try { SendThread.Abort(); } catch { } break; }
            }
        }

        private void SendMessages()
        {
            while (true)
            {
                try
                {
                    Console.Write(Name + ": ");
                    string Message = Console.ReadLine();
                    socket.Send(Encoding.ASCII.GetBytes(Message));
                }
                catch
                { break; }
            }
        }

        public byte[] RemoveNull(byte[] data)
        {
            int i = data.Length - 1;
            while (data[i] == 0)
            {
                --i;
                if (i <= 0)
                    break;
            }
            byte[] newData = new byte[i + 1];
            Array.Copy(data, newData, i + 1);
            return newData;
        }
    }
}
